package com.manager.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.manager.entity.Member;
import com.manager.mapper.MemberMapper;
import com.manager.service.IMemberService;
import com.manager.util.JwtUtil;
import com.manager.vo.LoginVo;
import com.manager.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class MemberService extends ServiceImpl<MemberMapper, Member> implements IMemberService {

    @Value("${avatar.path}")
    private String avatarPath;

    @Override
    public Map<String, String> login(LoginVo loginVo) {
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getAccount,loginVo.getAccount());
        wrapper.eq(Member::getPassword,loginVo.getPassword());
        Member member = baseMapper.selectOne(wrapper);

        Map<String,String> map = new HashMap<>();
        if(member == null){
            map.put("key","1");
            map.put("message","账户或者密码错误");
            return map;
        }

        String token = JwtUtil.createToken(member.getMemberName(), member.getAccount());
        map.put("key","2");
        map.put("message","登录成功");
        map.put("token",token);
        return map;
    }

    @Override
    public int register(RegisterVo registerVo) {
        Member member = new Member();
        BeanUtil.copyProperties(registerVo, member);
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getAccount,member.getAccount());

        Long count = baseMapper.selectCount(wrapper);
        if(count > 0){
            throw new RuntimeException("账号已存在");
        }

        long id = System.currentTimeMillis();
        member.setMemberId(id+"");

        return baseMapper.insert(member);
    }

    @Override
    public Member getInfo(String token) {
        String account = JwtUtil.getAccount(token);
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getAccount,account);

        return baseMapper.selectOne(wrapper);
    }

    @Override
    public String upload(MultipartFile file) {

        try {
            // 获取上传的文件名
            String fileName = IdUtil.randomUUID() + ".jpg";
            // 设置保存文件的路径
            String filePath = avatarPath + fileName;

            // 创建文件对象
            File dest = new File(filePath);
            // 判断目标文件的父目录是否存在，如果不存在则创建
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 将上传的文件保存到目标位置
            file.transferTo(dest);

            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public ResponseEntity<Resource> getAvatar(String fileName) {

        String filePath = avatarPath + fileName;
        // 创建文件对象
        File file = new File(filePath);
        if (!file.exists()) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        try {
            // 使用FileSystemResource封装文件并设置响应头
            Resource resource = new FileSystemResource(file);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);

            // 返回带有头像文件的ResponseEntity
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @Override
    public int updateMember(Member member) {
        if(member == null || member.getMemberId() == null){
            return -1;
        }
        LambdaQueryWrapper<Member> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Member::getMemberId,member.getMemberId());

        Member mInBase = baseMapper.selectOne(wrapper);

        if(!(member.getAvatar() != null && member.getAvatar().equals(mInBase.getAvatar()))){
            //删除原头像文件
            String originFilePath = avatarPath + mInBase.getAvatar();
            File file = new File(originFilePath);
            file.delete();
        }

        //更新数据库
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getMemberId, member.getMemberId());
        return baseMapper.update(member, queryWrapper);

    }

}
